<template>
	<el-tabs v-model="activeName" class="custom_top personal_container">
		<el-tab-pane label="个人信息" name="information">
			<h2>个人信息</h2>
			<el-form ref="userForm" :model="userForm" :rules="userRules" class="user_info_form">
				<div class="avatar">
					<el-form-item>
						<sw-image-uploader v-model="userForm.picId" accept="jpg,png"></sw-image-uploader>
					</el-form-item>
				</div>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="姓名" prop="userName">
							<el-input v-model="userForm.userName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电子邮箱" prop="account">
							<el-input v-model="userForm.account" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="出生日期" prop="birthDate">
							<el-date-picker v-model="userForm.birthDate" type="date" placeholder="请选择出生日期" value-format="yyyy-MM-dd" style="width: 100%"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="用户性别" prop="sex">
							<el-radio-group v-model="userForm.sex">
								<el-radio v-for="(item, index) in dictEnums['USER_SEX']" :key="index" :label="item.value">{{ item.msg }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="用户民族" prop="ethnic">
							<nation-select v-model="userForm.ethnic" placeholder="请选择用户民族" style="width: 100%"></nation-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="职称" prop="filed1">
							<el-input v-model="userForm.filed1"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电话" prop="phone">
							<el-input v-model="userForm.phone"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位" prop="filed2">
							<el-input v-model="userForm.filed2"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位类型" prop="filed3">
							<el-select v-model="userForm.filed3" placeholder="请选择单位类型" disabled style="width: 100%">
								<el-option v-for="(item, index) in dictEnums['DEPART_TYPE']" :key="index" :label="item.content" :value="item.content"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位属性" prop="filed4">
							<el-select v-model="userForm.filed4" placeholder="请选择单位属性" disabled style="width: 100%">
								<el-option v-for="(item, index) in dictEnums['DEPART_ATTRS']" :key="index" :label="item.content" :value="item.content"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="角色">
							<el-tag v-for="(item, index) in userForm.roleList" :key="index">{{ item.name }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-button type="primary" @click="handleSaveInfo()">保存</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-tab-pane>
		<el-tab-pane label="密码修改" name="updatepass">
			<h2>密码修改</h2>
			<p>
				设置您的
				<font color="#4361ee">新密码</font>
			</p>
			<el-form ref="passForm" :model="passForm" :rules="passRules" class="user_pass_form">
				<el-form-item label="输入您的旧密码" prop="oldPassword">
					<el-input type="password" v-model="passForm.oldPassword" placeholder="输入您的旧密码" show-password></el-input>
				</el-form-item>
				<el-form-item label="输入您的新密码" prop="password">
					<el-input type="password" v-model="passForm.password" placeholder="输入您的新密码" show-password></el-input>
				</el-form-item>
				<el-form-item label="确认您的新密码" prop="password2">
					<el-input type="password" v-model="passForm.password2" placeholder="确认您的新密码" show-password></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleUpdatePass()">修改</el-button>
				</el-form-item>
			</el-form>
		</el-tab-pane>
	</el-tabs>
</template>

<script>
import rsa from '@/utils/rsa';
import { mapGetters } from 'vuex';
import nationSelect from '@/components/nationSelect';
import { getDepartTree } from '@/api/system/tbSysDept';
import { userDetail, updateUserBase, updatePassNeedOld } from '@/api/system/tbSysUser';
export default {
	components: { nationSelect },
	data() {
		const validatePass = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请输入新密码'));
			} else if (!this.passRule.rules.test(value)) {
				callback(new Error(this.passRule.message));
			} else {
				callback();
			}
		};
		const validateSame = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请输入新密码'));
			} else if (this.passForm.password !== value) {
				callback(new Error('您两次输入的密码不一致'));
			} else {
				callback();
			}
		};
		return {
			loading: false,
			activeName: 'information',
			defaultProps: {
				label: 'name',
				children: 'childList'
			},
			userForm: {},
			userRules: {
				userName: { required: true, message: '请输入姓名', trigger: 'blur' },
				filed1: { required: true, message: '请选择职称', trigger: 'change' },
				phone: [
					{ required: true, message: '请输入电话号码', trigger: 'blur' },
					{ pattern: /^((0\d{2,3}-\d{7,8})|(1[3-9]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }
				],
				filed2: { required: true, message: '请输入单位', trigger: 'blur' }
			},
			passForm: {},
			passRules: {
				oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
				password: [
					{ required: true, message: '请输入新密码', trigger: 'blur' },
					{ validator: validatePass, trigger: 'blur' }
				],
				password2: [
					{ required: true, message: '请重新输入新密码', trigger: 'blur' },
					{ validator: validateSame, trigger: 'blur' }
				]
			}
		};
	},
	computed: {
		...mapGetters(['userInfo', 'siteInfo', 'dictEnums']),
		passRule() {
			let rules = null;
			let message = null;
			let len1 = this.siteInfo.passwordLen1;
			let len2 = this.siteInfo.passwordLen2;
			let level = this.siteInfo.passwordLevel;
			if (level === '1') {
				message = '请输入' + len1 + '到' + len2 + '位数字或字母或特殊字符(@$!%*#?&)';
				rules = new RegExp('^[A-Za-z0-9$@$!%*#?&]{' + len1 + ',' + len2 + '}$');
			} else if (level === '2') {
				message = '请输入' + len1 + '到' + len2 + '位数字和字母或特殊字符(@$!%*#?&)';
				rules = new RegExp('^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9$@$!%*#?&]{' + len1 + ',' + len2 + '}$');
			} else if (level === '3') {
				message = '请输入' + len1 + '到' + len2 + '位数字和字母和特殊字符(@$!%*#?&)';
				rules = new RegExp('^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[$@$!%*#?&])[A-Za-z0-9$@$!%*#?&]{' + len1 + ',' + len2 + '}$');
			}
			return { rules, message };
		}
	},
	watch: {
		userInfo: {
			async handler(data) {
				this.loading = true;
				await this.getUserData(data.id);
				this.loading = false;
			},
			immediate: true
		}
	},
	methods: {
		//获取用户信息
		async getUserData(id) {
			let result = await userDetail(id).then((res) => res.data);
			if (result.code === '0') {
				let datas = !!result.data && result.data.length > 0 ? result.data[0] : {};
				this.userForm = { ...datas, picId: !!datas.picId && datas.picId !== '-1' ? datas.picId : '' };
			}
		},

		//保存用户信息
		handleSaveInfo() {
			this.$refs['userForm'].validate((valid) => {
				if (!valid) return false;
				this.saveUserInfoRequest();
			});
		},

		//保存用户信息请求
		async saveUserInfoRequest() {
			let params = { ...this.userForm };
			let result = await updateUserBase(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `个人信息保存成功`);
			}
		},

		//修改用户密码
		handleUpdatePass() {
			this.$refs['passForm'].validate((valid) => {
				if (!valid) return false;
				this.updatePassRequest();
			});
		},

		//格式化修改密码参数
		formatPasswordParams() {
			let params = { ...this.passForm, id: this.userInfo.id };
			params['password'] = rsa.rsaPublicData(params.password);
			params['oldPassword'] = rsa.rsaPublicData(params.oldPassword);
			delete params.password2;
			return params;
		},

		//修改用户密码请求
		async updatePassRequest() {
			let params = this.formatPasswordParams();
			let result = await updatePassNeedOld(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `用户密码修改成功`);
				//this.$local.clear();
				//window.location.reload();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.personal_container::v-deep {
	display: flex;
	flex-direction: column;
	height: 100%;
	background-color: #fff;

	.el-tabs__item {
		font-size: 16px;
	}

	.el-tabs__content {
		flex: 1;
		overflow: auto;
	}

	.el-tab-pane {
		padding: 20px;

		h2 {
			font-size: 20px;
		}

		p {
			margin-top: 10px;
		}
	}
}

.user_info_form::v-deep {
	display: flex;
	margin-top: 20px;

	.avatar {
		width: 150px;
		height: 150px;
		flex-shrink: 0;
		margin-right: 40px;
	}

	.el-form-item__label {
		float: none;
		display: block;
		text-align: left;
		font-weight: bold;
		line-height: 1;
		margin-bottom: 10px;
	}
	
	.el-input {
		line-height: 1;
	}
	
	.el-tag {
		margin-right: 8px;
	}
}

.user_pass_form::v-deep {
	margin-top: 20px;

	.el-form-item__label {
		font-weight: bold;
		line-height: 1;
		margin-bottom: 10px;
	}
}
</style>
